var context_path = "/kangchenjunga";

document.addEventListener('DOMContentLoaded', function() {
	initAside();
	var sidenav_elem = document.querySelectorAll('.sidenav');
	var sidenav_instance = M.Sidenav.init(sidenav_elem);

	var dropdown_elem = document.querySelectorAll('.dropdown-trigger');
	var dropdown_instance = M.Dropdown.init(dropdown_elem, {
		'coverTrigger' : false
	});

	var coll_elem = document.querySelectorAll('.collapsible');
	var coll_instance = M.Collapsible.init(coll_elem);

	var select_elem = document.querySelectorAll('select');
	var select_instance = M.FormSelect.init(select_elem);

	var fab_elem = document.querySelectorAll('.fixed-action-btn');
	var fab_instance = M.FloatingActionButton.init(fab_elem, {
		// direction: 'left'
		hoverEnabled : false
	});

	var modal_elem = document.querySelectorAll('.modal');
	var modal_instance = M.Modal.init(modal_elem);

	var datepicker_elem = document.querySelectorAll('.datepicker');
	var datepicker_instance = M.Datepicker.init(datepicker_elem, {
		format : 'yyyy-mm-dd'
	});

});

$(document).ready(function() {
	if($('#table_body_div').length > 0) {
		const ps = new PerfectScrollbar('#table_body_div', {
			wheelSpeed : 2,
			wheelPropagation : true,
			minScrollbarLength : 20
		});
	}

	if($('.modal-content').length > 0) {
		const ps1 = new PerfectScrollbar('.modal-content', {
			wheelSpeed : 2,
			wheelPropagation : true,
			minScrollbarLength : 20
		});
	}

	if($('#selected-div').length > 0) {
		const ps2 = new PerfectScrollbar('#selected-div', {
			wheelSpeed : 2,
			wheelPropagation : true,
			minScrollbarLength : 20
		});
	}

	$('#select_all').click(function() {
		if ($(this).prop('checked') == true) {
			$('td input[type="checkbox"]:not(:checked)').prop('checked', true);
			$('#select_all').prop('checked', true);
		} else {
			$('td input[type="checkbox"]:checked').prop('checked', false);
			$('#select_all').prop('checked', false);
		}

	});

	$('.date-picker').datepicker({
		format : "yyyy-mm-dd",
		language : "zh-CN",
		autoclose : true
	}).on('hide', function(e) {
		M.updateTextFields();
		M.validate_field($(this));
	});

});

function getCookie(c_name) {
	if (document.cookie.length>0) {
		  c_start = document.cookie.indexOf(c_name + "=");
		if (c_start != -1) {
			c_start = c_start + c_name.length + 1;
			c_end = document.cookie.indexOf(";", c_start);
			if (c_end == -1)
				c_end = document.cookie.length;
			return document.cookie.substring(c_start, c_end);
		}
	}
	return "";
}

function updatePwdSubmit(id) {
	var input_elems = $('#modal3 .modal-content input');
    input_elems.each(function(){
      M.validate_field($(this));
    });
    if($('#modal3 input[name="newPassword"]').val() != $('#modal3 input[name="confirmPassword"]').val() || $('#modal3 input[name="confirmPassword"]').val() == '') {
    	$('#modal3 input[name="confirmPassword"]').addClass('invalid');
    } else {
    	$('#modal3 input[name="confirmPassword"]').removeClass('invalid');
    }
    var invalid_input_elems = $('#modal3 .modal-content input.invalid');
    if(invalid_input_elems.length > 0) {
      return false;
    }
	$.ajax({
		url: context_path + "/api/v1/users/" + id + "/password",
		data: '{"oldPassword" : "' + $('#modal3 input[name="oldPassword"]').val()
			+ '", "newPassword" : "' + $('#modal3 input[name="newPassword"]').val() + '"}',
		contentType: "application/json;charset=utf-8",
		type: "POST",
		headers: {
			Accept: "application/json"
		},
		success: function(data, textStatus) {
			// console.log(data);
			swal({
				title: "",
				text: "保存成功!",
				icon: "success",
				timer: 2000,
			}).then(function(value) {
				$("#modal3 input[type=reset]").trigger("click");
				$('#modal3').modal('close');
                // window.location.reload();
            });
		},
		error: function (data, textStatus, errorThrown) {
		    // console.log(data);
			swal({
				title: "",
				text: data.responseJSON.message,
				icon: "error",
				// timer: 2000,
			});
			M.updateTextFields();
		}
	});
}

// 校验手机号
function checkPhone(phone) {
	var reg = /^1[3|4|5|6|7|8|9][0-9]{9}$/; // 验证规则
	// var reg = /^1[0-9]{10}$/;

	var flag = reg.test(phone); // true

	return flag;
}

// 校验用户名
function checkUserName(username) {
	// var reg = /^[\u4E00-\u9FA5\uF900-\uFA2D]|\w\w{3,29}$/;//用户名必须为1-16为字母或数字
	var reg = /^\w\w{3,29}$/;// 用户名必须为1-16为字母或数字
	var flag = reg.test(username);// 校验
	return flag;
}

var active_menu ='';

function initAside() {
	active_menu = $('#page-title').attr('active-menu');

	if(active_menu) {
		$('#' + active_menu).addClass('active').parents('li').addClass('active');
		$('#' + active_menu + ' a').addClass('active gradient-shadow gradient-45deg-light-blue-pro').css("display", "block");
		$('#' + active_menu).siblings().removeClass('active').children('li').removeClass('active');
	}

}

function formParamsSerialize($form_) {
	var params = new Array();
	$form_.each(function() {
		$(this).val($.trim($(this).val()));
		params.push(this);
	})
	return $(params).serialize();
}

function dateFormat(dateStr, fmt) {
	var date = new Date(dateStr);
	var o = {
       "M+" : date.getMonth()+1,                 // 月份
       "d+" : date.getDate(),                    // 日
       "h+" : date.getHours(),                   // 小时
       "m+" : date.getMinutes(),                 // 分
       "s+" : date.getSeconds(),                 // 秒
       "q+" : Math.floor((date.getMonth()+3)/3), // 季度
       "S"  : date.getMilliseconds()             // 毫秒
    };
    if(/(y+)/.test(fmt)) {
    	fmt = fmt.replace(RegExp.$1, (date.getFullYear()+"").substr(4 - RegExp.$1.length));
    }
    for(var k in o) {
    	if(new RegExp("("+ k +")").test(fmt)){
    		fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));
        }
    }
	return fmt;
}
